package com.qiaofang.service.impl;/**
 * @program: channel-bomc
 * @description: 分销公司外部关联关系
 * @author: Seven.wang
 * @create: 2020-01-16 17:08
 **/

import com.qiaofang.common.config.SystemConfig;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.response.SuccessfulResponseFactory;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.dto.BindCompanyDTO;
import com.qiaofang.entity.CompanyRelation;
import com.qiaofang.entity.OtherCompany;
import com.qiaofang.repository.CompanyRelationRepository;
import com.qiaofang.repository.OtherCompanyRepository;
import com.qiaofang.service.OtherCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: channel-bomc
 *
 * @description: 分销公司外部关联关系
 *
 * @author: Seven.wang
 *
 * @create: 2020-01-16 17:08
 **/
@Service
public class OtherCompanyServiceImpl implements OtherCompanyService {

    @Autowired
    private OtherCompanyRepository otherCompanyRepository;

    @Autowired
    private CompanyRelationRepository companyRelationRepository;

    @Override
    public void batchAdd(List<BindCompanyDTO> list) {
        List<Long> companyIds = list.stream().map(item -> item.getCompanyId()).collect(Collectors.toList());
        List<OtherCompany> otherCompanyList = otherCompanyRepository.listOtherCompany(companyIds);
        List<OtherCompany> newOtherCompany = new ArrayList<>();
        if(!CollectionUtils.isEmpty(otherCompanyList)){
            for (OtherCompany oc : otherCompanyList){
                newOtherCompany = buildOtherCompanyList(oc, list);
            }
        }else{
            newOtherCompany = buildOtherCompanyList(null, list);
        }
        otherCompanyRepository.saveAll(newOtherCompany);
    }

    /**
     *  构建外部分销关联关系
     * @param oc        已存在的关联关系
     * @param list
     * @return
     */
    private List<OtherCompany> buildOtherCompanyList(OtherCompany oc, List<BindCompanyDTO> list){
        List<OtherCompany> newOtherCompany = new ArrayList<>();
        for (BindCompanyDTO bc : list){
            if(oc != null && (oc.getChannelCompanyId().equals(bc.getCompanyId()) && DelFlagEnum.DEL.getNo().equals(oc.getIsDeleted()))){
                oc.setCompanyUuid(bc.getCompanyUuid());
                oc.setBindCompanyType(bc.getBindCompanyType());
                oc.setSyncMode(bc.getSyncMode());
                oc.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                oc.setUpdateTime(new Date());
                newOtherCompany.add(oc);
            }else{
                /**
                 * 判断 该公司uuid是否已存在v10绑定
                 */
                OtherCompany o = otherCompanyRepository.getOtherCompany(bc.getCompanyUuid());
                if ( null != o ) {
                    return null;
                }
                /**
                 * 如果存在相同绑定，直接修改该绑定的状态
                 */
                OtherCompany company = new OtherCompany();
                List<OtherCompany> otherCompanies = otherCompanyRepository.listOtherCompanyByUuid(bc.getCompanyUuid(),bc.getCompanyId());
                if (null != otherCompanies && otherCompanies.size() >0) {
                    company.setId(otherCompanies.get(0).getId());
                }
                company.setAppid(SystemConfig.appId);
                company.setAppkey(SystemConfig.appKey);
                company.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                company.setChannelCompanyId(bc.getCompanyId());
                company.setCompanyName(bc.getCompanyName());
                company.setCompanyUuid(bc.getCompanyUuid());
                company.setBindCompanyType(bc.getBindCompanyType());
                company.setSyncMode(bc.getSyncMode());
                company.setCreateTime(new Date());
                newOtherCompany.add(company);
            }
        }
        return newOtherCompany;
    }

    @Override
    public CommonResponse batchUpdate(List<BindCompanyDTO> list) {
        CommonResponse response = new CommonResponse();
        List<Long> companyIds = list.stream().map(item -> item.getCompanyId()).collect(Collectors.toList());
        List<OtherCompany> otherCompanyList = otherCompanyRepository.listOtherCompany(companyIds);
        Map<Long, OtherCompany> otherCompanyMap = otherCompanyList.stream().collect(Collectors.toMap(OtherCompany::getChannelCompanyId, dto -> dto, (curr, old) -> curr));
        List<OtherCompany> updateOtherCompany = new ArrayList<>();
        for (BindCompanyDTO bc : list) {
            if(otherCompanyMap != null && otherCompanyMap.get(bc.getCompanyId()) != null){
                OtherCompany oc = otherCompanyMap.get(bc.getCompanyId());
                /**
                 * 判断 该公司uuid是否已存在v10绑定
                 */
                OtherCompany o = otherCompanyRepository.getOtherCompany(bc.getCompanyUuid());
                if ( null != o && (!(o.getId()).equals(oc.getId()))) {
                    response.setResponseCode("-1");
                    response.setResponseMessage("修改的公司UUID,已绑定其他商户！");
                    return response;
                }
                oc.setCompanyUuid(bc.getCompanyUuid());
                oc.setBindCompanyType(bc.getBindCompanyType());
                oc.setSyncMode(bc.getSyncMode());
                oc.setUpdateTime(new Date());
                updateOtherCompany.add(oc);
            }else{
                /**
                 * 如果存在相同绑定，直接修改该绑定的状态
                 */
                OtherCompany company = new OtherCompany();
                List<OtherCompany> otherCompanies = otherCompanyRepository.listOtherCompanyByUuid(bc.getCompanyUuid(),bc.getCompanyId());
                if (null != otherCompanies && otherCompanies.size() >0) {
                    company.setId(otherCompanies.get(0).getId());
                }
                /**
                 * 判断 该公司uuid是否已存在v10绑定
                 */
                OtherCompany o = otherCompanyRepository.getOtherCompany(bc.getCompanyUuid());
                if ( null != o ) {
                    /**
                     * 判断传入进来的数据该公司uuid绑定了几家分销公司
                     */
                    List<BindCompanyDTO> bind = list.stream().filter(b -> b.getCompanyUuid().equals(bc.getCompanyUuid())).collect(Collectors.toList());
                    if (bind.size() > 1){
                        response.setResponseCode("-1");
                        response.setResponseMessage("新增的公司UUID,已绑定其他商户！！");
                        return response;
                    }
                    company.setId(o.getId());
                }
                company.setAppid(SystemConfig.appId);
                company.setAppkey(SystemConfig.appKey);
                company.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                company.setChannelCompanyId(bc.getCompanyId());
                company.setCompanyName(bc.getCompanyName());
                company.setCompanyUuid(bc.getCompanyUuid());
                company.setBindCompanyType(bc.getBindCompanyType());
                company.setSyncMode(bc.getSyncMode());
                company.setCreateTime(new Date());
                updateOtherCompany.add(company);
            }
        }
        otherCompanyRepository.saveAll(updateOtherCompany);
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @Override
    public void deleteOtherCompany(Long companyId) {
        otherCompanyRepository.deleteOtherCompany(companyId);
    }

    @Override
    public List<BindCompanyDTO> selectOtherCompanyList(Long companyId) {
        List<CompanyRelation> listCompany = companyRelationRepository.listCompanyId(companyId);
        if(CollectionUtils.isEmpty(listCompany)){
            return null;
        }
        List<Long> ids = listCompany.stream().map(item -> item.getAgentCompany()).collect(Collectors.toList());
        List<OtherCompany> list = otherCompanyRepository.listOtherCompany(ids);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<BindCompanyDTO> bindCompanys = list.stream().filter((e) -> DelFlagEnum.UNDEL.getNo().equals(e.getIsDeleted())).map(item -> {
            BindCompanyDTO bc = new BindCompanyDTO();
            bc.setCompanyId(item.getChannelCompanyId());
            bc.setCompanyName(item.getCompanyName());
            bc.setCompanyUuid(item.getCompanyUuid());
            bc.setBindCompanyType(item.getBindCompanyType());
            bc.setSyncMode(item.getSyncMode());
            return bc;
        }).collect(Collectors.toList());
        return bindCompanys;
    }

    @Override
    public List<OtherCompany> selectOtherCompanyListByDevCompany(Long companyId) {
        List<CompanyRelation> listCompany = companyRelationRepository.listCompanyId(companyId);
        if(CollectionUtils.isEmpty(listCompany)){
            return null;
        }
        List<Long> ids = listCompany.stream().map(item -> item.getAgentCompany()).collect(Collectors.toList());
        List<OtherCompany> list = otherCompanyRepository.listOtherCompany(ids);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list;
    }

    @Override
    public OtherCompany getOtherCompanyByChannelCompanyId(Long companyId) {
        return otherCompanyRepository.getOtherCompanyByChannelCompanyId(companyId);
    }
}
